<script setup lang="ts">
import { useSidebarStore } from '@/stores/sidebar';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getDynamicRouterAsync } from '@/api/services/MenuService';
import { getUserInfo } from '@/api/services/LoginService';
import { getIconComponent } from '@/utils/icons';
import type { Menu } from '@/types/Menu';

const sidebarStore = useSidebarStore();
const router = useRouter();

// 动态菜单数据
const dynamicMenus = ref<Menu[]>([]);
const loading = ref(false);

// 获取动态菜单
const fetchDynamicMenus = async () => {
  try {
    loading.value = true;
    const userInfo = getUserInfo();
    if (!userInfo?.id) {
      console.error('用户信息不存在');
      return;
    }

    const response = await getDynamicRouterAsync({ userId: userInfo.id });
    if (response.success && response.data) {
      dynamicMenus.value = response.data as Menu[];
    } else {
      console.error('获取动态菜单失败:', response.message);
    }
  } catch (error) {
    console.error('获取动态菜单异常:', error);
  } finally {
    loading.value = false;
  }
};

// 处理菜单点击
const handleMenuClick = (menu: Menu) => {
  if (menu.component && menu.path) {
    router.push(menu.path);
  }
};

// 组件挂载时获取动态菜单
onMounted(() => {
  fetchDynamicMenus();
});
</script>

<template>
  <el-menu :default-active="$route.path" class="el-menu-vertical-demo" :collapse="sidebarStore.isCollapse" router>
    <!-- 首页菜单项 -->
    <el-menu-item index="/main/home" @click="router.push('/main/home')">
      <el-icon>
        <component :is="getIconComponent('el-icon-house')" />
      </el-icon>
      <template #title>首页</template>
    </el-menu-item>

    <!-- 动态菜单 -->
    <div v-if="loading" class="menu-loading">
      <el-skeleton animated>
        <template #template>
          <el-skeleton-item variant="text" style="width: 80%; margin: 10px 0;" />
          <el-skeleton-item variant="text" style="width: 60%; margin: 10px 0;" />
        </template>
      </el-skeleton>
    </div>

    <template v-else>
      <!-- 渲染一级菜单 -->
      <template v-for="menu in dynamicMenus" :key="menu.id">
        <!-- 有子菜单的情况 -->
        <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="menu.path">
          <template #title>
            <el-icon>
              <component :is="getIconComponent(menu.meta.icon)" />
            </el-icon>
            <span>{{ menu.meta.title }}</span>
          </template>
          <!-- 渲染子菜单 -->
          <el-menu-item v-for="child in menu.children" :key="child.id" :index="child.path"
            @click="handleMenuClick(child)">
            <el-icon>
              <component :is="getIconComponent(child.meta.icon)" />
            </el-icon>
            <template #title>{{ child.meta.title }}</template>
          </el-menu-item>
        </el-sub-menu>

        <!-- 没有子菜单的情况 - 一级菜单作为目录，不可点击 -->
        <el-sub-menu v-else :index="menu.path">
          <template #title>
            <el-icon>
              <component :is="getIconComponent(menu.meta.icon)" />
            </el-icon>
            <span>{{ menu.meta.title }}</span>
          </template>
          <!-- 空子菜单项，显示提示信息 -->
          <el-menu-item disabled>
            <template #title>暂无子菜单</template>
          </el-menu-item>
        </el-sub-menu>
      </template>
    </template>
  </el-menu>
</template>

<style>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.menu-loading {
  padding: 10px;
}
</style>
